package io.renren.modules.demo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.demo.dao.ShareUserDao;
import io.renren.modules.demo.dao.SharedCardDao;
import io.renren.modules.demo.dto.LeaveMeaasgeDTO;
import io.renren.modules.demo.dto.ShareUserDTO;
import io.renren.modules.demo.dto.SharedCardDTO;
import io.renren.modules.demo.entity.NewsEntity;
import io.renren.modules.demo.entity.ShareUserEntity;
import io.renren.modules.demo.entity.SharedCardEntity;
import io.renren.modules.demo.service.SharedCardService;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.crypto.signers.ISOTrailers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2021-05-24
 */
@Service
public class SharedCardServiceImpl extends CrudServiceImpl<SharedCardDao, SharedCardEntity, SharedCardDTO> implements SharedCardService {

    @Autowired
    private SharedCardDao sharedCardDao;

    @Autowired
    private ShareUserDao shareUserDao;

    @Override
    public QueryWrapper<SharedCardEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<SharedCardEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }

    /**
     * 根据用户昵称查询所有分享你
     */
    public List<SharedCardDTO> getAllShareByName(String name) {
        //根据名称查询用户
        ShareUserDTO shareUserDTO = shareUserDao.selectUserByName(name);
        if (shareUserDTO == null) {
            return null;
        }

        return sharedCardDao.getAllShareById(shareUserDTO.getShareId());
    }

    /**
     * 查询所有分享
     *
     * @return
     */
    public List<SharedCardDTO> getAllShare() {
        return sharedCardDao.getAllShare();
    }

    @Override
    public Object shareUri(String uri, String msg, MultipartFile img) throws Exception {
        // 图片路径
        String imgUrl = null;
        String uploadDir = "./img";
        String filename = upload(img, uploadDir, img.getOriginalFilename());
        if (!StringUtils.isEmpty(filename)) {
            imgUrl = new File(uploadDir).getName() + "/" + filename;
        }

        return share(uri);
    }

    public String upload(MultipartFile file, String path, String fileName) throws Exception {
// 生成新的文件名
        String realPath = path + "/" + UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));
        File dest = new File(realPath);
// 判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
// 保存文件
        file.transferTo(dest);
        return dest.getName();
    }

    /**
     * 解析分享链接
     *
     * @param uri
     * @throws IOException
     */
    public Object share(String uri) throws IOException {
        //0 创建链接
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        Request.Builder requestBuilder = new Request.Builder();

        //1 解析出真正的链接地址
        Request request = requestBuilder.url(uri).method("GET", null).build();
        Response response = client.newCall(request).execute();
        HttpUrl redirectUrl = response.request().url();


        //2 解析重定向数据
        request = requestBuilder.url(redirectUrl).method("GET", null).build();
        String itemId = request.url().pathSegments().get(1);
        String userId = request.url().queryParameter("user_id");

        //3 获取用户信息
        String userUri = "https://h5.pipix.com/bds/webapi/user/detail/?user_id=" + userId;
        request = requestBuilder.url(userUri).method("GET", null).build();
        response = client.newCall(request).execute();
        String sharedUserJsonData = response.body().string();
        JSONObject sharedUserJson = JSONObject.parseObject(sharedUserJsonData);
        ShareUserDTO shareUserDTO = parseShaerUserDTO(sharedUserJson);
        ShareUserDTO shareUserDTO1 = shareUserDao.selectByShareId(shareUserDTO.getShareId());
        System.out.println(shareUserDTO1);
        if (shareUserDTO1 == null) {
            ShareUserEntity shareUserEntity = ConvertUtils.sourceToTarget(shareUserDTO, ShareUserEntity.class);
            int insert = shareUserDao.insert(shareUserEntity);
            System.out.println(insert);
        }
        //4 获取接口数据
        String itemUri = "https://h5.pipix.com/bds/webapi/item/detail/?item_id=" + itemId;
        request = requestBuilder.url(itemUri).method("GET", null).build();
        response = client.newCall(request).execute();
        String sharedCardJsonData = response.body().string();
        JSONObject sharedCardJson = JSONObject.parseObject(sharedCardJsonData);
        SharedCardDTO sharedCardDTO = parseSharedCardDTO(sharedCardJson, Long.parseLong(userId));
        ShareUserDTO shareUserDTO2 = parseShaerdUserDTO(sharedCardJson);
        ShareUserDTO shareUserDTO3 = shareUserDao.selectByShareId(shareUserDTO2.getShareId());
        if (shareUserDTO3 == null) {
            ShareUserEntity shareUserEntity = ConvertUtils.sourceToTarget(shareUserDTO2, ShareUserEntity.class);
            int insert = shareUserDao.insert(shareUserEntity);
            System.out.println(insert);
        }
        SharedCardEntity entity = ConvertUtils.sourceToTarget(sharedCardDTO, SharedCardEntity.class);
        sharedCardDao.insert(entity);
        System.out.println(sharedCardDTO);
        return "Success";
    }

    /**
     * 解析出被分享人的信息
     */
    private ShareUserDTO parseShaerdUserDTO(JSONObject sharedUserJson) {
        JSONObject jsonItem = sharedUserJson.getJSONObject("data").getJSONObject("item").getJSONObject("author");
        return parseUser(jsonItem);
    }

    /**
     * 解析出分享人的信息
     *
     * @param sharedUserJson
     * @return
     */
    private ShareUserDTO parseShaerUserDTO(JSONObject sharedUserJson) {
        JSONObject jsonItem = sharedUserJson.getJSONObject("data").getJSONObject("user");
        return parseUser(jsonItem);
    }

    private ShareUserDTO parseUser(JSONObject jsonUser) {
        Long id = jsonUser.getLong("id");
        String description = jsonUser.getString("description");
        String name = jsonUser.getString("name");
        String uri = jsonUser.getJSONObject("avatar").getString("uri");
        ShareUserDTO shareUserDTO = new ShareUserDTO();
        shareUserDTO.setShareId(id);
        shareUserDTO.setShareSign(description);
        shareUserDTO.setShareNickname(name);
        shareUserDTO.setSharePhoto(uri);
        return shareUserDTO;
    }

    /**
     * 获取分享内容
     *
     * @param itemObject
     * @param shareId
     * @return
     */
    private SharedCardDTO parseSharedCardDTO(JSONObject itemObject, Long shareId) {
        JSONObject jsonItem = itemObject.getJSONObject("data").getJSONObject("item");
        String content = jsonItem.getString("content");
        Long item_id = jsonItem.getLong("item_id");
        String image_url = jsonItem.getJSONObject("share").getString("image_url");
        Date create_time = jsonItem.getDate("create_time");
        Long sharedId = jsonItem.getJSONObject("author").getLong("id");
        JSONObject jsonAvatar = jsonItem.getJSONObject("avatar");
        SharedCardDTO sharedCardDTO = new SharedCardDTO();
        sharedCardDTO.setSharedId(sharedId);
        sharedCardDTO.setShareId(shareId);
        sharedCardDTO.setSharedItemId(item_id);
        sharedCardDTO.setSharedContent(content);
        sharedCardDTO.setSharedUri(image_url);
        sharedCardDTO.setSharedCreateTime(create_time);
        return sharedCardDTO;
    }


    private LeaveMeaasgeDTO parseLeaveMeaasgeDTO(JSONObject itemObject) {

        LeaveMeaasgeDTO leaveMeaasgeDTO = new LeaveMeaasgeDTO();

//        leaveMeaasgeDTO.setLeaveMsg();
        return leaveMeaasgeDTO;
    }


}